<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            class="addRoleBtn"
            @click="dialogRoleVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :data="roleList"
        border
        stripe
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-row
              v-for="(item, index) in row.children"
              :key="item.id"
              :class="['dbbottom', index === 0 ? 'dbtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="closeTag(row, item.id)" closable>{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'dbtop', 'vcenter']"
                >
                  <!-- 渲染二级 -->
                  <el-col :span="6"
                    ><el-tag
                      @close="closeTag(row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 渲染三级 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning "
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="closeTag(row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            >
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="editRole(row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-star-off"
              @click="setRightDialog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogRoleVisible"
      width="50%"
      @close="roleDialogclosed"
    >
      <!-- 添加角色表单 -->
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="addRoleRules"
        label-width="90px"
        :status-icon="true"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleVisible"
      width="50%"
      @close="editFormClosed"
    >
      <!-- 添加角色表单 -->
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        label-width="90px"
        :rules="editFormRules"
        :status-icon="true"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="`'` + roleNames + `'` + '的权限列表'"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="clearDefkeys"
    >
      <el-tree
        ref="setRightRef"
        node-key="id"
        show-checkbox
        :data="rightList"
        default-expand-all
        :props="defaultProps"
        :default-checked-keys="defkeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created() {
    this.getRoleList()
  },
  data() {
    return {
      // 获取角色数据
      roleList: [],
      // 隐藏或显示添加角色对话框
      dialogRoleVisible: false,
      // 添加角色的数据
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 校验规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' },
          { max: 20, message: '长度不大于20个字符', trigger: 'blur' }
        ]
      },
      // 隐藏或显示编辑角色对话框
      editRoleVisible: false,
      // 编辑角色数据
      editRoleForm: {},
      // 编辑角色表单规则
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' },
          { max: 20, message: '长度不大于20个字符', trigger: 'blur' }
        ]
      },
      // 分配权限对话框是否显示
      rightDialogVisible: false,
      // 权限列表树状图
      rightList: [],
      // 树型控件数据
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点
      defkeys: [],
      // 暂时存储打开的权限设置对应的roleId和roleName
      roleIds: '',
      roleNames: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 对话框关闭后表单重置
    roleDialogclosed() {
      this.$refs.roleFormRef.resetFields()
    },
    // 提交添加用户表单信息
    addRoleInfo() {
      // 校验信息
      this.$refs.roleFormRef.validate(async valid => {
        if (!valid) return false
        // 校验通过进行发送
        const { data: res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) {
          this.$message.error('角色添加失败')
        }
        // 添加成功
        this.$message.success('角色添加成功')
        // 关闭对话框
        this.dialogRoleVisible = false
        // 刷新列表
        this.getRoleList()
      })
    },
    // 打开编辑角色对话框
    async editRole(id) {
      // 打开对话框
      this.editRoleVisible = true
      // 获取该用户角色数据
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户角色信息数据失败')
      }
      this.editRoleForm = res.data
    },
    // 关闭编辑角色对话框后重置
    editFormClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 提交角色编辑信息
    editRoleInfo() {
      // 校验表单
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return false
        // 校验通过进行发送
        const { data: res } = await this.$http.put(
          `roles/${this.editRoleForm.roleId}`,
          this.editRoleForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('角色修改失败')
        }
        // 发送成功
        this.$message.success('角色修改成功')
        // 关闭对话框
        this.editRoleVisible = false
        // 刷新列表内
        this.getRoleList()
      })
    },
    // 删除角色
    deleteRole(row) {
      // 删除提示
      this.$confirm(`此操作将永久删除'${row.roleName}', 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 确认删除
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${row.id}`)
          // 判断是否删除失败
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          // 删除成功，刷新列表
          this.getRoleList()
          // 删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        // 取消删除
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除Tag
    closeTag(role, rightId) {
      // 弹框提示
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 进行删除
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          // 判断是否发送成功
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          // 重新渲染
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 打开分配权限对话框
    async setRightDialog(row) {
      // 获取列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 储存数据
      this.rightList = res.data
      // 储存roleId和roleName
      this.roleIds = row.id
      this.roleNames = row.roleName
      // 递归获取三级节点的id
      this.getLeafKeys(row, this.defkeys)
      // 显示对话框
      this.rightDialogVisible = true
    },
    // 通过递归获取三级节点的id，并保存到defkeys中
    getLeafKeys(node, arr) {
      // 当前node节点不包含chilren 属性，
      // 则返回当前节点的id
      if (!node.children) {
        return arr.push(node.id)
      }
      // 还有children 属性，进行递归
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭权限列表对话框时清空defkeys
    clearDefkeys() {
      this.defkeys = []
    },
    async allotRight() {
      // 存取选中节点的keys
      const keyId = [
        ...this.$refs.setRightRef.getCheckedKeys(),
        ...this.$refs.setRightRef.getHalfCheckedKeys()
      ]
      // 发送角色授权信息
      const { data: res } = await this.$http.post(
        `roles/${this.roleIds}/rights`,
        {
          rids: keyId.join(',')
        }
      )
      // 授权失败
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      // 授权成功，刷新列表
      this.$message.success('分配权限成功')
      this.getRoleList()
      // 关闭对话框
      this.rightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.addRoleBtn {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
</style>
